import React, { useState, useEffect, useRef } from 'react'
import { Input } from 'antd';
import '@/style/sider/fileSearch.scss'
import useKeyPress from '@/hooks/useKeyPress'
import config from '../common/Common';

export default function FileSearch({ title, onFileSearch }) {
    const [inputActive, setInputActive] = useState(false);
    const [value, setValue] = useState('');
    const enterPressed = useKeyPress(13)
    const escPressed = useKeyPress(27)
    let inputFocus = useRef(null)
    const setSearch = (active) => {
        setInputActive(active);
        setValue('');
        onFileSearch('')
    }
    useEffect(() => {
        if (enterPressed && inputActive) {
            onFileSearch(value)
        }
        if (escPressed && inputActive) {
            setSearch(false)
        }
    })
    useEffect(() => {
        if (inputActive) {
            inputFocus.current.focus();
        }
    }, [inputActive])
    const IconFont = config.IconFont;

    return (
        <div
            className='fileSearch'
            style={{
                padding: (inputActive ? '0 10px 0 0' : '0 20px 0 20px')
            }}
        >
            {
                inputActive
                    ? <Input
                        ref={inputFocus}
                        placeholder="搜索"
                        className='fileSearch-input'
                        onChange={(e) => { setValue(e.target.value) }}
                    />
                    : <p className='fileSearch-title'>{title}</p>
            }
            {/* <svg className="icon fileSearch-search" aria-hidden="true">
                <use xlinkHref="#iconsousuo" />
            </svg> */}
            <IconFont
                type={inputActive ? 'iconcancel01' : 'iconsousuo'}
                className='fileSearch-search'
                onClick={() => { setSearch(!inputActive) }}
            />
        </div >
    )
}
